<template>
  <dtDialog
    :title="orgTextMap[orgDialogStatus]"
    :visible.sync="orgDialogFormVisible"
    :is-loading="loading"
    :footer-slot="orgDialogStatus === 'detail'? true : false"
    @closeDialog="orgResetTemp()"
    @comfirmBtn="onSubmit()"
  >
    <el-form
      ref="orgDataForm"
      slot="content"
      :rules="orgRules"
      :model="orgTemp"
      label-position="right"
      label-width="82px"
      style="width: 100%;overflow-x: auto;"
      :disabled="orgDialogStatus === 'detail'"
    >
      <el-form-item v-if="selectedorgFlag && orgTemp.orgParentId != -1" ref="orgParentIdRef" label="上级组织" prop="orgParentId">
        <el-popover v-model="visible" placement="bottom-start" trigger="click" :disabled="orgDialogStatus === 'detail'">
          <el-tree
            ref="tree"
            :style="{'--themecolor':themeActive,'--lightOpacity':lightTheme}"
            class="tree orgManage"
            width="100%"
            :data="treePopover"
            node-key="id"
            :current-node-key="orgTemp.orgParentId"
            lazy
            :highlight-current="true"
            :load="loadPopover"
            :props="defaultProps"
            :default-checked-keys="defaultId"
            :default-expand-all="false"
            :expand-on-click-node="false"
            @node-click="selectParentOrg"
          />
          <el-input slot="reference" v-model="parentOrgName" :readonly="false" @input="orgInput" @focus="orgFocus" />
        </el-popover>
      </el-form-item>
      <el-form-item label="组织名称" prop="orgName">
        <el-input v-model.trim="orgTemp.orgName" maxlength="30" show-word-limit class="limit" />
      </el-form-item>
      <el-form-item label="组织编码" prop="orgCode">
        <el-input v-model.trim="orgTemp.orgCode" :disabled="orgDialogStatus === 'update'" maxlength="30" show-word-limit class="limit" />
      </el-form-item>
      <el-form-item label="排序" prop="orgSort">
        <!-- <el-input v-model.trim="orgTemp.orgSort" @input="e => (orgTemp.orgSort = e.replace(/[^\d]/g, ''))" /> -->
        <el-input v-model.trim="orgTemp.orgSort" maxlength="8" :oninput="initPositiveInteger()" show-word-limit class="limit" />
      </el-form-item>
      <el-form-item label="备注" prop="orgRemark">
        <el-input
          v-model.trim="orgTemp.orgRemark"
          maxlength="200"
          type="textarea"
          show-word-limit
          class="limit"
        />
      </el-form-item>
    </el-form>
  </dtDialog>
</template>
<script>
import hrOrganizationApi from '@/framework/api/hrOrganization'
import { positiveInteger } from '@/framework/utils/validate'
export default {
  data() {
    return {
      loading: false,
      defaultId: [],
      orgDialogFormVisible: false,
      orgDialogStatus: '',
      selectedorgFlag: true,
      currentOrg: {},
      orgTextMap: {
        update: '修改组织',
        create: '新增组织',
        detail: '查看详情',
        createChildren: '新增下级组织'
      },
      orgTemp: {
        orgParentId: '',
        parentOrgName: '',
        orgName: '',
        orgCode: '',
        orgSort: '',
        orgRemark: ''
      },
      parentOrgName: '',
      orgName: '',
      visible: false,
      tree: [],
      treePopover: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      orgRules: {
        orgParentId: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请选择上级组织名称'))
            } else if (value === this.orgTemp.parentId) {
              callback(new Error('上级组织不可修改为当前组织'))
            } else {
              callback()
            }
          }
        }],
        orgName: [{
          required: true,
          message: '请输入组织名称',
          trigger: 'blur'
        }, {
          pattern: /^[^#@%&*¥$*]+$/,
          message: '不要输入特殊字符'
        }],
        orgCode: [{
          required: true,
          message: '请输入组织编码',
          trigger: 'blur'
        },
        {
          pattern: /^[A-Za-z0-9_]+$/,
          message: '请输入字母或数字'
        }
        ],
        orgSort: [{
          required: false,
          message: '请输入组织顺序',
          trigger: 'blur'
        }
        ],
        orgRemark: [{
          required: false,
          pattern: /^[^#@%&*¥$*]+$/,
          message: '不要输入特殊字符'
        }]
      },
      editUservisible: false
    }
  },
  computed: {
    theme() {
      return this.$store.getters.theme
    },
    themeActive() {
      return this.$store.state.settings.theme
    },
    lightTheme() {
      return this.theme + '19'
    }
  },
  watch: {
    // filterText(val) {
    //   this.$refs.tree.filter(val)
    // }
    // parentOrgName(val) {
    //   hrOrganizationApi.getOrgListTreeNode({ orgId: 0, orgName: val }).then((res) => {
    //     const data = res.data.map((item, index) => {
    //       item.orgParentId = item.id
    //       item.parentOrgName = item.name
    //       return item
    //     })
    //     this.treePopover = data
    //   })
    // }
  },
  created() {
    // this.initTree()
  },
  methods: {
    // 获取组织树
    initTree() {
      const that = this
      hrOrganizationApi.fetchList().then((res) => {
        that.tree = res.data
        // this.selectedOrg = res.data[0]
        // this.currentKey = res.data[0].id
        // this.$nextTick(() => {
        //   this.$refs.tree.setCurrentKey(res.data[0].id)
        // })
      })
    },
    orgInput() {
      hrOrganizationApi.getOrgListTreeNode({ orgId: 0, orgName: this.parentOrgName }).then((res) => {
        const data = res.data.map((item, index) => {
          item.orgParentId = item.id
          item.parentOrgName = item.name
          return item
        })
        this.treePopover = data
      })
      if (this.parentOrgName == '') {
        this.parentOrgName = ''
        this.orgTemp.orgParentId = ''
      }
    },
    // orgBlur() {
    //   if (this.parentOrgName == '') {
    //     this.parentOrgName = ''
    //     this.orgTemp.orgParentId = ''
    //   }
    // },
    orgFocus() {
      const param = this.currentOrg.nodeParentId ? { orgId: this.currentOrg.nodeParentId } : { orgId: 0, orgName: this.parentOrgName }
      hrOrganizationApi.getOrgListTreeNode(param).then((res) => {
        if (this.currentOrg.nodeParentId) {
          const data = res.data.filter((item, index) => {
            if (this.orgTemp.orgParentId == item.id) {
              item.orgParentId = item.id
              item.parentOrgName = item.name
              return item
            }
          })
          this.treePopover = data
        } else {
          const data = res.data.map((item, index) => {
            item.orgParentId = item.id
            item.parentOrgName = item.name
            return item
          })
          this.treePopover = data
        }
      })
    },
    // 校验排序规则
    initPositiveInteger(data) {
      return positiveInteger(data)
    },
    // 选择组织
    selectParentOrg(data) {
      this.visible = false
      this.orgTemp.orgParentId = data.id
      this.parentOrgName = data.name
      this.currentOrg = data
      this.defaultId = []
      this.defaultId.push(this.orgTemp.orgParentId)
      this.$refs.orgParentIdRef.clearValidate()
    },
    // 关闭弹窗
    orgResetTemp() {
      this.orgTemp = {
        orgParentId: ''
      }
      this.parentOrgName = ''
      this.currentOrg = {}
    },
    // 打开新增弹窗
    openOrg(row, type) {
      this.selectedorgFlag = true
      this.orgDialogFormVisible = true
      if (type == 'add') {
        this.orgDialogStatus = 'create'
      } else if (type == 'addChildren') {
        this.orgDialogStatus = 'create'
        this.orgTemp.orgParentId = row.orgId
        this.parentOrgName = row.orgName
      } else if (type == 'update') {
        this.orgDialogStatus = 'update'
        hrOrganizationApi.detail(row.orgId).then((res) => {
          this.orgTemp = Object.assign({}, res.data)
          this.orgTemp.orgParentId = res.data.orgParentId
          this.parentOrgName = res.data.parentName
        })
      } else if (type == 'detail') {
        this.orgDialogStatus = 'detail'
        hrOrganizationApi.detail(row.orgId).then((res) => {
          this.orgTemp = Object.assign({}, res.data)
          this.orgTemp.orgParentId = res.data.orgParentId
          this.parentOrgName = res.data.parentName
        })
      }
      this.$nextTick(() => {
        this.$refs['orgDataForm'].clearValidate()
      })
    },

    // 创建请求
    async onSubmit() {
      this.$refs['orgDataForm'].validate(async(valid) => {
        if (valid) {
          this.loading = true
          const orgTempData = Object.assign({}, this.orgTemp)
          try {
            if (this.$parent.tableData[0].children.length == 0) {
              this.$set(this.$parent.tableData[0], 'hasChildren', true)
            }
            if (this.orgDialogStatus === 'create') {
              const res = await hrOrganizationApi.add(orgTempData)
              if (res.success) {
                this.initTree()
                this.$parent.getList(orgTempData.orgParentId)
                this.orgDialogFormVisible = false
                this.$dtMessage({
                  message: '新增成功',
                  type: 'success'
                })
              }
            } else if (this.orgDialogStatus === 'update') {
              const res = await hrOrganizationApi.edit(orgTempData)
              if (res.success) {
                this.initTree()
                this.$parent.getList(orgTempData.orgParentId)
                this.orgDialogFormVisible = false
                this.$dtMessage({
                  message: '修改成功',
                  type: 'success'
                })
              }
            }
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    // 删除请求
    deleteOrg(row) {
      this.$dtMessageBox({ title: '提示', message: '确定要删除“' + row.orgName + '”吗?', type: 'warning' }).then(() => {
        hrOrganizationApi.delete({ orgId: row.orgId }).then(res => {
          this.initTree()
          this.$parent.getList()
          this.$dtMessage({
            message: '删除成功',
            type: 'success'
          })
        }).catch(() => {
        // 取消不做操作
        })
      })
    },
    loadPopover(tree, resolve) {
      let orgid = ''
      if (!tree.data || tree.data.length == 0) {
        orgid = 0
      } else {
        orgid = tree.data.id
      }
      hrOrganizationApi.getOrgListTreeNode({ orgId: orgid }).then((res) => {
        const data = res.data
        resolve(data)
      })
    }
  }
}
</script>
<style>

</style>
